import QtQuick 1.1
import com.nokia.meego 1.0
import FileSystemModel 1.0

VisualDataModel {
    id: filesVisualModel

    property variant view: null

    signal fileClicked(string filePath)

    model: FileSystemModelItem {
        id: fileSystemModelItem
        /*
        onDirectoryLoaded: {
            console.log("filesVisualModel.onDirectoryLoaded directory=" + directory);
        }
        */
    }

    delegate: InfoItemDelegate {
        id: listItem
        arrowEnabled: fileIsDirectory
        Column {
            id: listItemContent
            /* Seems there is no easy way to translate the fileIcon QUrl into an image-source without own ImageProvider :-/
            Image {
                //asynchronous: true
                source: fileIcon
            }
            */
            Label {
                text: fileName
                font.weight: Font.Bold
                font.pointSize: 16
            }
            Row {
                id: columnRow
                spacing:10
                Label {
                    text: fileSize
                    font.weight: Font.Light
                    font.pointSize: 16
                }
                Label {
                    text: fileType
                    font.weight: Font.Light
                    font.pointSize: 16
                }
            }
        }
        onItemClicked: {
            if (fileIsDirectory) {
                if (model.hasModelChildren) {
                    filesVisualModel.view.model.rootIndex = filesVisualModel.view.model.modelIndex(index)
                    //filesVisualModel.rootIndex = filesVisualModel.modelIndex(index)
               }
            } else {
                var idx = filesVisualModel.view.model.modelIndex(index);
                //var idx = filesVisualModel.model.modelIndex(index);
                var role = filesVisualModel.model.role('FilePathRole');
                var data = filesVisualModel.model.data(idx, role)
                if (data != null && data != undefined)
                    filesVisualModel.fileClicked(data)
            }
        }
    }

    Component.onDestruction: {
        console.log("FileSystemModel.onDestruction")
    }

    function setView(view, directory) {
        filesVisualModel.view = view;

        // One time function used to set the initial QModelIndex rootIndex *after*
        // the directory is loaded. That seems to be needed for whatever reason
        // to make setting the initial directory working as expected.
        function initialLoad() {
            filesVisualModel.model.directoryLoaded.disconnect(initialLoad);
            filesVisualModel.view.model.rootIndex = filesVisualModel.model.directoryIndex();
        }
        filesVisualModel.model.directoryLoaded.connect(initialLoad);

        filesVisualModel.view.model.rootIndex = filesVisualModel.model.setDirectory(directory);
    }
}
